<template>
  <!--封装页面滚动-->
  <div ref="wrapper">
    <slot></slot>
  </div>
</template>

<script type="text/ecmascript-6">
  // better-scroll 用法父容器要position,不然刷新better-scroll不识别
  // 要保证dom重新渲染,要高度计算的时候,要重新refresh()
  // fastclick的冲突 加上class(needsclick)
  import BScroll from 'better-scroll'
  export default{
    props: {
      probeType: {
        type: Number,
        default: 1
      },
      click: {
        type: Boolean,
        default: true
      },
      scrollX: {
        type: Boolean,
        default: false
      },
      // 监听数据
      data: {
        // 异步加载后数据传入,来识别高度
        type: Array,
        default: null
      },
      // 监听滚动
      listenScroll: {
        type: Boolean,
        default: false
      },
      // 是否开启上拉加载
      pullup: {
        type: Boolean,
        default: false
      },
      // 在滚动之前做点事情
      beforeScroll: {
        type: Boolean,
        default: false
      }
    },
    mounted() {
      this.$nextTick(() => {
        this._initScroll()
      })
    },
    methods: {
      _initScroll() {
        if (!this.$refs.wrapper) {
          return
        }
        let options = {
          probeType: this.probeType,
          click: this.click,
        }
        if (this.scrollX) {
          options=Object.assign({}, options, {
            scrollX: this.scrollX,
            eventPassthrough: 'vertical'
          })
        }
        console.log(options)
        this.scroll = new BScroll(this.$refs.wrapper, options)

        if (this.pullup) {
          // 快滚到底部的时候触发
          this.scroll.on('scrollEnd', () => {
            if (this.scroll.y <= (this.scroll.maxScrollY + 50)) {
              this.$emit('scrollToEnd')
            }
          })
        }
        if (this.listenScroll) {
          this.scroll.on('scroll', (pos) => {
            this.$emit('scroll', pos)
          })
        }
        if (this.beforeScroll) {
          this.scroll.on('beforeScrollStart', () => {
            this.$emit('beforeScroll')
          })
        }
      },
      // 默认开启better-scroll
      enable() {
        this.scroll && this.scroll.enable()
      },
      // 关闭better-scroll
      disable() {
        this.scroll && this.scroll.disable()
      },
      refresh() {
        this.scroll && this.scroll.refresh()
      },

      scrollTo() {
        this.scroll && this.scroll.scrollTo.apply(this.scroll, arguments)
      },
      scrollToElement() {
        this.scroll && this.scroll.scrollToElement.apply(this.scroll, arguments)
      }
    },
    watch: {
      // data变化了,重新计算scroll
      data() {
        this.$nextTick(() => {
          this.refresh()
        })
      }
    }
  }
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
</style>
